import { useEffect, useState } from 'react';
import { Button, Checkbox, Form, Input, notification } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import styles from './index.module.scss';
import { useDispatch } from 'react-redux'
import { setUserInfo } from '@/reducers/main';
import { login } from '@/service'
import Cookies from 'js-cookie';
import { useTranslation } from 'react-i18next';
import { compile, uncompile } from '@/utils'
const FormItem = Form.Item;

export default props => {
    const [notificationApi, contextHolder] = notification.useNotification();
    const [form] = Form.useForm();
    const { t } = useTranslation();
    const initState = () => ({
        loading: false
    }),
        [state, setState] = useState(initState),
        navigate = useNavigate(),
        dispatch = useDispatch();
    // 进入页面判断是否保存了账号密码
    useEffect(() => {
        const userRemberInfo = localStorage.getItem("portal_userRemberInfo");
        form.setFieldsValue({
            name: '',
            password: '',
            remember: false,
        });
        if (userRemberInfo) {
            const obj = JSON.parse(userRemberInfo);
            form.setFieldsValue({
                name: obj.name,
                password: uncompile(obj.password),
                remember: true,
            });
        } else {
            setTimeout(() => {
                document.getElementById("username")?.focus();
            }, 0);
        }

    }, [form]);
    const onSubmit = async () => {
        try {
            const values = await form.validateFields();
            const { name, password } = values;
            const params = {
                name: name.trim(),
                password
            };
            setState((prevState) => ({ ...prevState, loading: true }));
            const res = await login(params);
            const { code, message, data } = res || {};
            if (code === 0) {
                const token = data?.token;
                const expire = data?.expire;
                const user = data?.user || {};
                Cookies.set('portal_token', token, { expires: expire });
                dispatch(setUserInfo(user));
                localStorage.setItem("portal_userinfo", compile(JSON.stringify(user)));
                if (form.getFieldValue('remember')) {
                    localStorage.setItem("portal_userRemberInfo", JSON.stringify({ name, password:compile(password)})           );
                } else {
                    localStorage.removeItem("portal_userRemberInfo");
                    form.resetFields();
                }
                navigate('/');
            } else {
                if (code == -4001) {
                    navigate('/support');
                } else {
                    notificationApi.error({
                        message: 'Login Failed',
                        description: message,
                    });
                }
            }
        } catch (error) {
            if (error?.message) {
                notificationApi.error({
                    message: 'Login Failed',
                    description: error?.message,
                });
            }
        } finally {
            setState((prevState) => ({ ...prevState, loading: false }));
        }
    };
    const goSign = () => {
        navigate('/signUp');
    }
    const fogetPsd = () => {
        navigate('/forgetPsd');
    }
    return (
        <div className={styles['container']}>
            {/* <div className={styles.logo}>
                <img src="/public/images/logo.svg" alt="" />
                <div>请登录</div>
            </div> */}
            <div className={styles.item}>
                <div className={styles.right}>
                    <div className={styles.title}>{t('login.loginBtn')}</div>
                    <Form
                        form={form}
                        style={{ width: 340, margin: '0 auto' }}
                        wrapperCol={{
                            span: 24,
                        }}
                        autoComplete="new-password"
                        className={styles.loginForm}
                    >
                        <FormItem
                            name="name"
                            rules={[{ required: true, message: t('login.usernameRules') }]}
                        >
                            <Input id='username' autoComplete="off" prefix={
                                <UserOutlined style={{ color: '#4e5969' }} />} type="text" placeholder={t('login.userNamePlaceholder')} />
                        </FormItem>
                        <FormItem
                            name="password"
                            rules={[{ required: true, message: t('login.passwordRules') }]}
                        >
                            <Input.Password
                                autoComplete="new-password"
                                prefix={
                                    <LockOutlined style={{ color: '#4e5969' }} />
                                }
                                placeholder={t('login.passwordPlaceholder')} />
                        </FormItem>
                        <FormItem shouldUpdate={(prevValues, currentValues) => prevValues.remember !== currentValues.remember}>
                            {({ getFieldValue, setFieldsValue }) => (
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <Checkbox
                                        className='custom-checkbox'
                                        checked={getFieldValue('remember')}
                                        onChange={(e) => setFieldsValue({ remember: e.target.checked })}
                                    >
                                        {t('login.text.rememberme')}
                                    </Checkbox>
                                    <div onClick={fogetPsd} className={styles.forgetText}>{t('login.text.forgetPassword')}</div>
                                </div>
                            )}
                        </FormItem>
                        <FormItem>
                            <Button loading={state?.loading} onClick={onSubmit} type="primary" htmlType="submit" className='custom-btn-primary' style={{ width: '100%', display: 'block', margin: '0 auto', height: '48px', lineHeight: '14px' }}>
                                {t('login.loginBtn')}
                            </Button>
                        </FormItem>
                    </Form>
                    <div className={styles.signBox}>
                        <div><span>{t('login.text.account')}</span><span onClick={goSign} className={styles.signUp}>{t('login.text.signUp')}</span></div>
                    </div>
                </div>
            </div>
            {contextHolder}
        </div>
    )
}
